package com.github.m6d21.sso.dao.user.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.m6d21.sso.dao.user.dao.IUserDao;
import com.github.m6d21.sso.dao.user.mapper.UserMapper;
import com.github.m6d21.sso.model.user.entity.User;
import com.github.m6d21.sso.model.user.qo.UserQO;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

/**
 *<p>
 *UserDaoImpl
 *</p>
 *
 * @author liuyang
 * @date 2018-12-05 Wed 22:28:19
 * @since 1.0.0
 */
@Repository("userDao")
public class UserDaoImpl implements IUserDao {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getById(Integer id) {
        return userMapper.get(id);
    }

    @Override
    public List<User> selectUsernamePassword(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Lists.newArrayList();
        }
        return userMapper.selectUsernamePassword(username, password);
    }

    @Override
    public boolean insertUser(User user) {
        int row = userMapper.insertUser(user);
        return row == 1;
    }

    @Override
    public boolean insertSelectiveUser(User user) {
        int row = userMapper.insertSelectiveUser(user);
        return row == 1;
    }

    @Override
    public boolean updateUserById(User user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        int row = userMapper.updateUserById(user);
        return row == 1;
    }

    @Override
    public boolean updateSelectiveUserById(User user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        int row = userMapper.updateSelectiveUserById(user);
        return row == 1;
    }

    @Override
    public List<User> query(UserQO userQO) {
        List<User> list = userMapper.query(userQO);
        return Optional.ofNullable(list).orElseGet(() -> new ArrayList<>(0));
    }

    @Override
    public List<User> selectUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return Lists.newArrayList();
        }
        return userMapper.selectList(new QueryWrapper<User>().eq("username", username).eq("disable",0));
    }

    @Override
    public boolean deleteById(Integer id) {
        if (id == null) {
            return false;
        }
        int row = userMapper.deleteById(id);
        return row == 1;
    }

    @Override
    public boolean deleteByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        int row = userMapper.deleteBatchIds(ids);
        return row == ids.size();
    }
}
